import axios from 'axios'
import { MessageBox, Message } from 'element-ui';
import Vue from 'vue'
// import store from '@/store'
// import { getToken } from '@/utils/auth'
import API from './webpackApi.js'

// create an axios instance
const service = axios.create({
//   baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  baseURL: '/api',
  // baseURL: API.url,
  // headers:{
  //   token:sessionStorage.getItem('token'),
  // },  
  // data:{
  //   token:sessionStorage.getItem('token'),
  // },
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    var token = sessionStorage.getItem('token');
    // config.productionTip = false;
    if(token){
      config.headers.Authorization = 'Bearer ' + token;
    }
    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['X-Token'] = getToken()
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    if(response.request.responseType && response.request.responseType == 'blob' && response.status == 200){
      return response;
    }
    if(res.code == 202 || res == ''){
      Message({
        message: res.message || res.msg || '服务器异常',
        type: 'error',
        duration: 5 * 1000
      })
      localStorage.clear();
      sessionStorage.clear();
      let url = window.location.href.split('#')[0];
      window.location.href = url+'#/login';
      return;
    }
    if (res.code !== 200) {
      Message({
        message: res.message || res.msg || '服务器异常',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(res);
    }else{
      return res.data
    }
    //   return res;
    //   // return Promise.reject(new Error(res.message || res.msg || 'Error'))
    // } else {
    //   return res
    // }
    // return res
  },
  error => {
    console.log(error.response);
    // console.log(error.response.data.message);
    Message({
      // message: error.message,
      message: error.response.data.message || '服务器异常',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error.response)
    // return error;
  }
)

export default service
